// main.js - 处理主界面功能

document.addEventListener('DOMContentLoaded', async () => {
  // 从localStorage获取当前用户和令牌
  const currentUser = JSON.parse(localStorage.getItem('currentUser'));
  const token = localStorage.getItem('token');
  
  if (!currentUser || !token) {
    // 如果没有用户信息或令牌，重定向到登录页面
    window.location.href = 'login.html';
    return;
  }
  
  // 显示欢迎信息
  document.getElementById('welcomeMessage').textContent = `欢迎，${currentUser.username}`;
  
  // 添加退出按钮事件
  document.getElementById('logoutBtn').addEventListener('click', () => {
    localStorage.removeItem('currentUser');
    localStorage.removeItem('token');
    window.location.href = 'login.html';
  });

  // 加载名片夹概览数据
  await loadFolderOverview();
});

/**
 * 加载名片夹概览数据
 */
async function loadFolderOverview() {
  try {
    // 检查令牌是否存在
    const token = localStorage.getItem('token');
    if (!token) {
      throw new Error('认证失败：未找到令牌');
    }
    
    // 获取名片夹列表（带详情）
    const foldersResponse = await window.api.folders.getAllWithDetails();
    
    if (!foldersResponse.success) {
      throw new Error('获取名片夹数据失败：' + (foldersResponse.message || ''));
    }
    
    const foldersList = foldersResponse.folders;
    
    // 清空现有表格内容（表头除外）
    const tableBody = document.querySelector('.overview table tbody') || document.createElement('tbody');
    tableBody.innerHTML = '';
    
    let totalCards = 0;
    
    // 如果没有名片夹，显示提示信息
    if (foldersList.length === 0) {
      const emptyRow = document.createElement('tr');
      emptyRow.innerHTML = '<td colspan="3" style="text-align: center;">暂无名片夹</td>';
      tableBody.appendChild(emptyRow);
      
      // 更新总计信息
      document.querySelector('.welcome p').innerHTML = 
        `您当前有 <strong>0</strong> 张名片，分布在 <strong>0</strong> 个名片夹中`;
        
      return;
    }
    
    // 处理每个名片夹并添加到表格中
    foldersList.forEach(folder => {
      // 累计总名片数
      totalCards += folder.cardCount;
      
      // 格式化日期
      let lastUpdated = '暂无更新';
      if (folder.lastUpdated) {
        lastUpdated = new Date(folder.lastUpdated).toLocaleDateString('zh-CN');
      }
      
      // 创建行
      const row = document.createElement('tr');
      row.innerHTML = `
        <td>${folder.name}</td>
        <td>${folder.cardCount}</td>
        <td>${lastUpdated}</td>
      `;
      
      tableBody.appendChild(row);
    });
    
    // 确保表格有tbody
    if (!document.querySelector('.overview table tbody')) {
      document.querySelector('.overview table').appendChild(tableBody);
    }
    
    // 更新总计信息
    document.querySelector('.welcome p').innerHTML = 
      `您当前有 <strong>${totalCards}</strong> 张名片，分布在 <strong>${foldersList.length}</strong> 个名片夹中`;
    
    // 显示表格，隐藏加载提示
    document.querySelector('.loading').style.display = 'none';
    document.querySelector('.overview table').style.display = 'table';
  } catch (error) {
    console.error('加载名片夹概览失败:', error);
    
    // 处理错误信息
    const errorMessage = error.message || '未知错误';
    const loadingElement = document.querySelector('.loading');
    
    if (loadingElement) {
      loadingElement.innerHTML = `
        <div style="color: #721c24; background-color: #f8d7da; padding: 10px; border-radius: 4px;">
          <p>加载名片夹数据失败: ${errorMessage}</p>
          <div style="margin-top: 10px;">
            <button onclick="location.reload()">重试</button>
            <button onclick="location.href='login.html'" style="margin-left: 10px;">重新登录</button>
          </div>
        </div>
      `;
    }
    
    // 如果是认证错误，提供登录选项
    if (errorMessage.includes('认证失败') || errorMessage.includes('unauthorized')) {
      localStorage.removeItem('currentUser');
      localStorage.removeItem('token');
      
      setTimeout(() => {
        alert('登录已过期，请重新登录');
        window.location.href = 'login.html';
      }, 1000);
    }
  }
} 